using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;

namespace Boggle.Net.Model
{
    public sealed partial class Tray
    {
        private readonly char[][] _tray;

        public const int Columns = 4;
        public const int Rows = 4;
        public const int Capacity = Columns * Rows;

        public Tray(ICollection<char> letters)
        {
            Contract.Requires<ArgumentNullException>(letters != null);
            Contract.Requires<ArgumentException>(letters.Count == Capacity);

            _tray = new char[Rows][];

            for (var row = 0; row < Rows; ++row)
                _tray[row] = letters.Skip(row * Columns).Take(Columns).ToArray();
        }

        public IEnumerable<Location> AllLocations
        {
            get
            {
                for (var row = 0; row < Rows; ++row)
                    for (var column = 0; column < Columns; ++column)
                        yield return new Location(column, row);
            }
        }

        public IEnumerable<char> AllLetters
        {
            get { return AllLocations.Select(LetterAt); }
        }

        public char LetterAt(Location location)
        {
            return _tray[location.Row][location.Column];
        }

        public override String ToString()
        {
            return String.Concat(AllLetters);
        }

        public static Tray FilledWith(char[] letters)
        {
            return new Tray(letters);
        }
    }
}